package com.tensquare.user.service;

import com.tensquare.user.dao.AdminDao;
import com.tensquare.user.pojo.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import utils.IdWorker;

import javax.persistence.Id;

/**
 * Created by WF on 2020/7/27 14:45
 */
@Service
public class AdminService {
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private AdminDao adminDao;
    //1.添加管理员
    public void add(Admin admin) {
        //1.0)设置管理员的id及对密码进行加密
        admin.setId(idWorker.nextId() + "");
        admin.setPassword(passwordEncoder.encode(admin.getPassword()));
        //1.1)保存到数据库 中
        adminDao.save(admin);
    }
    //2.管理员登录
    public Admin login(String loginname, String password) {
      //2.1)根据用户名查询管理员对象
        Admin loginAdmin = adminDao.findByLoginname(loginname);
        //2.2)判断是否存在
        if(loginAdmin != null && passwordEncoder.matches(password,loginAdmin.getPassword())){
            return loginAdmin;
        }
        return null;
    }
    //3.根据id删除管理员
    public void delete(String adminId) {
        adminDao.deleteById(adminId);
    }
}
